package news

class EasyUIController {

    static responseFormats = ['json']

    def index() {
        render(view:"EasyUIView")
    }

    def createNews(){
        def re = []
        def p = ProductType.findById(params.productType)
        if (p){
            def n = new News(title: params.title,
                    URL:params.URL,
                    productType: p,
                    createDate: new Date())
            n.save(flush: true)
            re.add([success:true,
                    id:n.id,
                    title:n.title,
                    URL:n.URL,
                    createDate:n.createDate,
                    ProduectTypeID: n.productType.id,
                    ProductType: n.productType.productTypeName])
        }
        else {
            re.add([errorMsg:"保存新闻错误"])
        }
        respond re

    }
    def updateNews(){
        def n = News.findById(params.id)
        def pt = ProductType.findById(params.productType)
        def re = []
        if (n){
            n.title = params.title
            n.URL = params.URL
            //n.createDate = params.createDate
            n.productType = pt
            n.save(flush: true)
            re.add([success: true,
                    title:n.title,
                    URL:n.URL,
                    createDate:n.createDate,
                    ProduectTypeID: n.productType.id,
                    ProductType: n.productType.productTypeName])
        }
        else{
            re.add([errorMsg:"保存新闻错误"])
        }
        respond re
    }
    def deleteNews(){
        def re = []
        def n = News.findById(params.id)
        if (n){
            n.hitLog.each {
                it.delete()
            }
            n.delete(flush: true)
            re = [success: true,errorMsg: "删除数据成功"]
        }
        else {
            re.add([success: false, errorMsg:"删除数据错误"])
        }
        respond re
    }
    def getProductTypeList(){
        def re = []
        ProductType.findAll().each {
            re.add([id:it.id,productTypeName:it.productTypeName])
        }
        respond re
    }
}